
package com.scalar.chiptrack.marketing.actions;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.LabelValueBean;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.marketing.MarketingForecast;
import com.scalar.chiptrack.marketing.dao.ForecastDAO;
import com.scalar.chiptrack.marketing.dao.MarketingDAO;
import com.scalar.chiptrack.marketing.forms.SettingForecastForm;
import com.scalar.chiptrack.sales.dao.NewCustomerDAO;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.users.User;


public final class SettingForecastAction extends ChipTrackAction
                                         implements Constants
{
    private static final String ACTION_NAME = "/settingForecast.do";
    public ActionForward execute(ActionMapping mapping,
                 ActionForm form,
                 HttpServletRequest request,
                 HttpServletResponse response)
    throws Exception
    {
        SettingForecastForm forecastForm = (SettingForecastForm) form;

        HashMap errors = new LinkedHashMap();
        request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
        HttpSession session = request.getSession ();
        HashMap info = new LinkedHashMap();
        request.setAttribute( SessionKeys.INFO_MESSAGES, info );

        String action = request.getParameter("action");
        User user = ( User ) request.getSession().getAttribute( SessionKeys.USER_KEY );
        if(user == null)
        {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString () );
            return( mapping.findForward( "login" ) );
        }
        // Added by veeru on 22nd July 2004
        String marketing = request.getParameter( "marketing" );
        //System.out.println("marketing:"+marketing);
        if ( user != null )
        {
            if ( ( "on".equalsIgnoreCase(marketing) && user.isActionAllowed ( Functionality.SETTING_MARKETING_FORECAST, User.USER_ACTION_MODIFY ) )
                 || ( !"on".equalsIgnoreCase(marketing) && user.isActionAllowed ( Functionality.SETTING_SALES_FORECAST, User.USER_ACTION_MODIFY ) )
               )
            {
                //System.out.println("false");
                request.setAttribute ( "showMessage", "FALSE" );
            }
            else
            {
                //System.out.println("true");
                request.setAttribute ( "showMessage", "TRUE" );
            }
        }
        if( "loadForecast".equalsIgnoreCase( action ) == true )
        {
            String customer = forecastForm.getCustomer();
            String product = forecastForm.getProduct();
            String endUser = forecastForm.getEndUser() ;
            request.setAttribute("mfgNo", product);  // Added by Gandhi on 23 July 2004
            int startMonth = forecastForm.getStartMonth();
            int monthCount = forecastForm.getMonthCount();
            int startYear = forecastForm.getYear() ;
            int year = forecastForm.getYear();

            String mkgForecast = forecastForm.getShowMkgForecast();
            String indForecast = forecastForm.getShowIndForecast();
            request.setAttribute( "startMonth", startMonth+"" );
            request.setAttribute( "monthCount", monthCount+"" );
            request.setAttribute( "year", startYear+"" );

            // Added by Veeru on 23rd August 2004 to persist the changed values
            String[] qty = request.getParameterValues( "qty" );
            String[] unitPrice = request.getParameterValues( "unitPrice" );
            String[] confidenceLevel = request.getParameterValues( "confidenceLevel" );

            if ( qty != null && unitPrice != null )
            {
                HashMap forecastMap = new HashMap();
                if( ( ( mkgForecast == null ) || ( mkgForecast.trim().length() == 0 ) || mkgForecast.equalsIgnoreCase("null") ) && confidenceLevel != null)
                {
                    for ( int i = 0; i < qty.length; i++ ) {
                        forecastMap.put( ( startMonth + i ) + "", new MarketingForecast( 0, "", "", "", 0, "", 0, Integer.parseInt( qty[ i ] ), Double.parseDouble( unitPrice[ i ] ), "", "", Float.parseFloat( confidenceLevel[ i ] ) ) );
                    }
                }
                else
                {
                     for ( int i = 0; i < qty.length; i++ ) {
                        forecastMap.put( ( startMonth + i ) + "", new MarketingForecast( 0, "", "", "", 0, "", 0, Integer.parseInt( qty[ i ] ), Double.parseDouble( unitPrice[ i ] ), "", "", 0.0f ) );
                    }
                }

                request.setAttribute( "forecastDetails", forecastMap );
            }
            try
            {
                loadForecastAndBacklogDetailsIntoRequest( request, user, customer, product,
                                                          startMonth, monthCount, year, mkgForecast, indForecast, endUser );
            }
            catch( Throwable t )
            {
                errors.put( "Internal Server Error", "Could not load required information" );
            }
        }

        else if( "saveForecast".equalsIgnoreCase( action ) == true )
        {
            String customer = forecastForm.getCustomer();
            String product = forecastForm.getProduct();
            String endUser = forecastForm.getEndUser() ;
            request.setAttribute("mfgNo", product);  // Added by Gandhi on 03 Aug 2004
            int startMonth = forecastForm.getStartMonth();
            int monthCount = forecastForm.getMonthCount();
            int startYear = forecastForm.getYear() ;
            int year = forecastForm.getYear();
            String mkgForecast = forecastForm.getShowMkgForecast();
            String indForecast = forecastForm.getShowIndForecast();

            request.setAttribute( "startMonth", startMonth+"" );
            request.setAttribute( "monthCount", monthCount+"" );
            request.setAttribute( "year", startYear+"" );


            // Step 1
            // Save Forecast Details
            try
            {
                String[] qty = request.getParameterValues( "qty" );
                String[] unitPrice = request.getParameterValues( "unitPrice" );
                // Added field confidenceLevel by Veeru on 20th August 2004
                String[] confidenceLevel = request.getParameterValues( "confidenceLevel" );
                try
                {
                    ForecastDAO.saveForecastDetails( user.getUserId(), product, customer, startMonth,
                                                     monthCount, year, qty, unitPrice, mkgForecast, confidenceLevel, endUser);

                    info.put( "Forecast details have been saved successfully", null );
                }
                catch( Throwable t )
                {
                    errors.put( "Internal Server Error", "Could not save Forecast information" );
                }
            }
            catch( Exception e )
            {
                e.printStackTrace();
                throw new ScalarException( "Could not save forecast detail into database", e );
            }


            // Step 2
            // Load Forecast and Backlog Details into Request Object
            try
            {
                loadForecastAndBacklogDetailsIntoRequest( request, user, customer, product,
                                                          startMonth, monthCount, year, mkgForecast, indForecast, endUser );
            }
            catch( Throwable t )
            {
                errors.put( "Internal Server Error", "Could not load required information" );
            }
            request.setAttribute("settingForecastForm", forecastForm );
        }
        else if( "fAndB".equalsIgnoreCase( action ) == true )
        {
            // setting customer and product lists
            request.setAttribute( "customerList", MarketingDAO.getAllCustomerNames() );
            //request.setAttribute( "productList", loadMarketingProducts() ); // Commented by Gandhi on 22 July 2004
            request.setAttribute( "productList", MarketingDAO.loadAllManufacturingPartNumbersWithMarketingPartNumbers() ); // Added by Gandhi on 23 July 2004
            request.setAttribute( "monthList", loadMonthList() );
            request.setAttribute ( "years", SalesOrderDAO.getYearList () );  // Added by Gandhi on 18th Aug 2004

            return mapping.findForward ( "forecastVsBacklogReportJsp" );
        }
        else if( "pAndA".equalsIgnoreCase( action ) == true )
        {
            // setting customer and product lists
            request.setAttribute( "customerList", MarketingDAO.getAllCustomerNames() );
            //request.setAttribute( "productList", loadMarketingProducts() ); // Commented by Gandhi on 22 July 2004
            request.setAttribute( "productList", MarketingDAO.loadAllManufacturingPartNumbersWithMarketingPartNumbers() ); // Added by Gandhi on 23 July 2004
            //request.setAttribute( "monthList", loadMonthList() );
            request.setAttribute ( "years", SalesOrderDAO.getYearList () );  // Added by Gandhi on 18th Aug 2004
            // Added by Gandhi on 8th Sep 2004
            //request.setAttribute( "endUserList", EndUserDAO.loadAllEndUsers() );
            request.setAttribute( "endUserList", NewCustomerDAO.loadAllOdms() );
            request.setAttribute( "salesPersonList", MarketingDAO.getAllSalesPersonsForCustomer() );
            request.setAttribute( "quarterList", loadQuarterList() );
            request.setAttribute( "currentQtr", getCurrentQuarter() );
            // Ends here - Gandhi
            return mapping.findForward ( "projectedVsActualReportJsp" );
        }
        //added by varma 11 sep 2004
       else if( "loadEndUser".equalsIgnoreCase( action ))
        {
            String customer = forecastForm.getCustomer();
            Calendar rightNow = Calendar.getInstance();
            forecastForm = new SettingForecastForm();
            forecastForm.setYear( rightNow.get( Calendar.YEAR ) );
            forecastForm.setStartMonth( rightNow.get( Calendar.MONTH ) );
            forecastForm.setMonthCount( 6 );
            request.setAttribute( "customerList", MarketingDAO.getAllCustomerNames() );
            request.setAttribute( "productList", MarketingDAO.loadAllManufacturingPartNumbersWithMarketingPartNumbers() );
            request.setAttribute( "monthList", loadMonthList() );
            request.setAttribute ( "years", SalesOrderDAO.getYearList () );
            request.setAttribute( "endUsersList",MarketingDAO.getEndUsersForCustomer( customer ) );
            forecastForm.setCustomer( customer );
            forecastForm.setShowMkgForecast( forecastForm.getShowMkgForecast() );
            request.setAttribute( "settingForecastForm", forecastForm );
            return( mapping.findForward("search") );
        }
        else
        {
            Calendar rightNow = Calendar.getInstance();
            forecastForm = new SettingForecastForm();
            forecastForm.setYear( rightNow.get( Calendar.YEAR ) );
            forecastForm.setStartMonth( rightNow.get( Calendar.MONTH ) );
            forecastForm.setMonthCount( 6 );    // default.. to be moved to some config file
            forecastForm.setShowMkgForecast( request.getParameter( "marketing" ) );
            request.setAttribute( "settingForecastForm", forecastForm );

            // Modified by veeru on 21st July 2004
            /*
            request.setAttribute( "startMonth", rightNow.get( Calendar.MONTH )+"" );
            request.setAttribute( "monthCount", "6" );
            //added by varma(13 jul 2004)
            request.setAttribute( "year", rightNow.get( Calendar.YEAR )+"" );
            request.setAttribute( "forecastDetails",      new HashMap() );
            request.setAttribute( "openBacklogByReqDate", new HashMap() );
            request.setAttribute( "holdBacklogByReqDate", new HashMap() );
            request.setAttribute( "openBacklogBySchDate", new HashMap() );
            request.setAttribute( "holdBacklogBySchDate", new HashMap() );
            request.setAttribute( "forecastDetailTotals", new HashMap() );
            request.setAttribute( "shippedOrders",        new HashMap() ); */

            request.setAttribute( "customerList", MarketingDAO.getAllCustomerNames() );
            //request.setAttribute( "productList", loadMarketingProducts() ); // Commented by Gandhi on 22 July 2004
            request.setAttribute( "productList", MarketingDAO.loadAllManufacturingPartNumbersWithMarketingPartNumbers() ); // Added by Gandhi on 23 July 2004
            request.setAttribute( "monthList", loadMonthList() );
            request.setAttribute ( "years", SalesOrderDAO.getYearList () );
            return mapping.findForward ( "search" );
            // End of Modified by veeru
        }

        // setting customer and product lists
        request.setAttribute( "customerList", MarketingDAO.getAllCustomerNames() );
        //request.setAttribute( "productList", loadMarketingProducts() ); // Commented by Gandhi on 22 July 2004
        request.setAttribute( "productList", MarketingDAO.loadAllManufacturingPartNumbersWithMarketingPartNumbers() ); // Added by Gandhi on 23 July 2004
        request.setAttribute( "monthList", loadMonthList() );
        request.setAttribute ( "years", SalesOrderDAO.getYearList () );

        return mapping.findForward( "success" );
    }


 // Commented by Gandhi on 22 July 2004
  /*
    private static ArrayList loadMarketingProducts() throws Exception
    {
        ArrayList parts = new ArrayList();
        Iterator list = FinishedGoodsDAO.loadAllFinishedGoods().iterator();

        while(list.hasNext())
        {
            FinishedGoods product = (FinishedGoods) list.next();
            parts.add( new LabelValueBean( product.getMarketingPartNo(), product.getMarketingPartNo() ) );
        }

        return parts;
    }
  */

    private static ArrayList loadMonthList()
    {
        ArrayList monthList = new ArrayList();

        monthList.add( new LabelValueBean( "January",   "0" ) );
        monthList.add( new LabelValueBean( "February",  "1" ) );
        monthList.add( new LabelValueBean( "March",     "2" ) );
        monthList.add( new LabelValueBean( "April",     "3" ) );
        monthList.add( new LabelValueBean( "May",       "4" ) );
        monthList.add( new LabelValueBean( "June",      "5" ) );
        monthList.add( new LabelValueBean( "July",      "6" ) );
        monthList.add( new LabelValueBean( "August",    "7" ) );
        monthList.add( new LabelValueBean( "September", "8" ) );
        monthList.add( new LabelValueBean( "October",   "9" ) );
        monthList.add( new LabelValueBean( "November",  "10" ) );
        monthList.add( new LabelValueBean( "December",  "11" ) );

        return monthList;
    }

    // Added by Gandhi on 8th Sep 2004
    public ArrayList loadQuarterList()
    {
        int start_qtr = 1;
        int end_qtr = 4;

        ArrayList yearList = new ArrayList ();
        for ( int year = start_qtr; year <= end_qtr; year++ )
        {
            yearList.add ( new LabelValueBean ( "Qtr " + year, year + "") );
        }
        yearList.add( new LabelValueBean ( "All", "All") );

        return yearList;
    }

    private String getCurrentQuarter()
    {
        String qtr = "1";
        Calendar c = Calendar.getInstance();
        int month = c.get( Calendar.MONTH );

        if( month > 8 )
        {
            qtr = "4";
        }
        else if( month > 5 )
        {
            qtr = "3";
        }
        else if( month > 2 )
        {
            qtr = "2";
        }
        else
        {
            qtr = "1";
        }

        return qtr;
    }

    // Ends here - Gandhi

    private static void loadForecastAndBacklogDetailsIntoRequest( HttpServletRequest request,
                                                                  User user,
                                                                  String customer,
                                                                  String product,
                                                                  int startMonth,
                                                                  int monthCount,
                                                                  int year,
                                                                  String mkgForecast,
                                                                  String indForecast,
                                                                  String endUser)
    throws Exception
    {
        HashMap forecastDetails = new HashMap();
        HashMap forecastDetailTotals = new HashMap();

        if( indForecast != null )
        {
            HashMap completeForecastDetails = ForecastDAO.loadCompleteForecastDetails( customer,
                                                                                       product,
                                                                                       startMonth,
                                                                                       (startMonth + monthCount),
                                                                                       year,
                                                                                       endUser,
                                                                                       mkgForecast); //added by varma

            request.setAttribute( "completeForecastDetails", completeForecastDetails );
        }

        forecastDetails = ForecastDAO.loadForecastDetailsByUser( user.getUserId(),
                                                                 customer,
                                                                 product,
                                                                 startMonth,
                                                                 (startMonth + monthCount),
                                                                 year,
                                                                 mkgForecast,
                                                                 endUser);
        if ( request.getAttribute( "forecastDetails" ) == null )
        {
            request.setAttribute( "forecastDetails", forecastDetails );
        }

        if( ( mkgForecast != null ) && ( mkgForecast.trim().length() != 0 ) )
        {
            forecastDetailTotals = ForecastDAO.loadForecastTotals( customer,
                                                              product,
                                                              startMonth,
                                                              (startMonth + monthCount),
                                                              year,
                                                              endUser,
                                                              mkgForecast );//added by varma

            request.setAttribute( "forecastDetailTotals", forecastDetailTotals );

            if( ( forecastDetails == null ) || ( forecastDetails.isEmpty() == true ) )
            {
                /*forecastDetails = ForecastDAO.loadForecastTotals( customer,
                                                                product,
                                                                startMonth,
                                                                (startMonth + monthCount),
                                                                year );
                */
                request.setAttribute( "forecastDetails", forecastDetailTotals );
            }
        }


        HashMap openBacklogByReqDate = ForecastDAO.loadSalesBacklog( customer,
                                                                     product,
                                                                     startMonth,
                                                                     (startMonth + monthCount),
                                                                     year,
                                                                     REQUESTED_DATE_CATEGORY,
                                                                     BACKLOG_TYPE_OPEN );

        request.setAttribute( "openBacklogByReqDate", openBacklogByReqDate );

        HashMap holdBacklogByReqDate = ForecastDAO.loadSalesBacklog( customer,
                                                                     product,
                                                                     startMonth,
                                                                     (startMonth + monthCount),
                                                                     year,
                                                                     REQUESTED_DATE_CATEGORY,
                                                                     BACKLOG_TYPE_HOLD );

        request.setAttribute( "holdBacklogByReqDate", holdBacklogByReqDate );

        HashMap openBacklogBySchDate = ForecastDAO.loadSalesBacklog( customer,
                                                                     product,
                                                                     startMonth,
                                                                     (startMonth + monthCount),
                                                                     year,
                                                                     SCHEDULED_DATE_CATEGORY,
                                                                     BACKLOG_TYPE_OPEN );

        request.setAttribute( "openBacklogBySchDate", openBacklogBySchDate );

        HashMap holdBacklogBySchDate = ForecastDAO.loadSalesBacklog( customer,
                                                                     product,
                                                                     startMonth,
                                                                     (startMonth + monthCount),
                                                                     year,
                                                                     SCHEDULED_DATE_CATEGORY,
                                                                     BACKLOG_TYPE_HOLD );

        request.setAttribute( "holdBacklogBySchDate", holdBacklogBySchDate );

        HashMap shippedOrders = ForecastDAO.loadShippedOrders( customer,
                                                               product,
                                                               startMonth,
                                                               (startMonth + monthCount),
                                                               year );

        request.setAttribute( "shippedOrders", shippedOrders );
    }

}